//
//  HTMicroblogLoginController.swift
//  WeiBoDemo
//
//  Created by 郝涛 on 16/4/18.
//  Copyright © 2016年 郝涛. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class HTMicroblogLoginController: UIViewController,UIWebViewDelegate {

    
    override func loadView() {
        
        view = WebView
        
        WebView.delegate = self
        //url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(REDIRECT_URI)")

        
        let request = NSURLRequest(URL: url!)
        WebView.loadRequest(request)
    }
    
   override func viewDidLoad() {
        super.viewDidLoad()
        
    
        setupUI()
    }
    //web开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    //加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
       SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //url转换为字符串
//        let urlString = request.URL?.absoluteString
        
        //判断前缀是否是www.baidu.com。
        if let urlString = request.URL?.absoluteString  where urlString.hasPrefix(REDIRECT_URI){
             //判断请求参数是否存在
            if let q = request.URL?.query{
                
                //获取code
                let code = q.substringFromIndex("code=".endIndex)

                //获取access_token
                getAccess_token(code)
            }
        }
 
        return true
    }
    
    //获取access_token
    func getAccess_token(code:String){
        
        //参数
        
        let param = [
            
//            必选	类型及范围	说明
//            client_id	true	string	申请应用时分配的AppKey。
//            client_secret	true	string	申请应用时分配的AppSecret。
//            grant_type	true	string	请求的类型，填写authorization_code
//            
//            grant_type为authorization_code时
//            必选	类型及范围	说明
//            code	true	string	调用authorize获得的code值。
//            redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
            "client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
            
                    ]
        
         let urlSting = "https://api.weibo.com/oauth2/access_token"
        
        
          HTNetworkTools.sharedNetworkTools.request(.POST, urlString: urlSting, param: param) { (response, error) -> () in
            if error != nil{
                //错误
                print("错误\(error)")
                return
            }
            //成功
//            print("成功啦\(response)")
            //由于response是可选值 所以我们要gr
            guard let dict = response as?[String:AnyObject] else{
                print("返回的不是一个字典")
                return
            }
            
            //转模型
            let token = HTUserInfoModel(dict:dict)
            
            //获取用户信息
//            self.getUserInfo()
            self.getUserInfo(token)
           
        }
        
        
    }
    
    
    //获取用户信息
    func getUserInfo(token:HTUserInfoModel){
//        请求参数
//        必选	类型及范围	说明
//        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//        uid	false	int64	需要查询的用户ID。
//        screen_name	false	string	需要查询的用户昵称。
        let param = [
            "access_token":token.access_token!,
            "uid":token.uid!
              ]
        
        
        
        let  urlString = "https://api.weibo.com/2/users/show.json"
           HTNetworkTools.sharedNetworkTools.request(HTRequestWay.GET, urlString:urlString , param: param) { (response, error) -> () in
            
            if error != nil{
                print(error)
                return
            }
            guard let dict = response as?[String:AnyObject]else{
                
                print("不是字典")
                return
            }
//            print(response)
            //对touken的昵称和头像赋值
            token.screen_name = dict["screen_name"]as?String
            token.avatar_large = dict["avatar_large"]as?String
     
            //对用户的信息保存
            HTUserAccountTools.sharedTools.saverAccount(token)
            
            //关闭界面
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //发送通知告诉appdelegate切换根控制器
                NSNotificationCenter.defaultCenter().postNotificationName(switchdefaultNotificationname, object: nil)
            })
            
            
        }
    }

    
    
    
    
    
    // MARK: - 监听方法
    @objc private func cancle(){
        dismissViewControllerAnimated(true, completion: nil)
    }

    @objc private func auto(){
       
        //自动填充
        let jsString = "document.getElementById('userId').value='779253298@qq.com';document.getElementById('passwd').value='13145210.'"
        //注入js
        WebView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }

    
    // MARK: - 设置导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        navigationItem.title = "微博登陆"
        
        
    }
    // MARK: - 懒加载控件
    private lazy var WebView: UIWebView = UIWebView()
    
}
